package com.qianbei.view;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.qianbei.R;
import com.qianbei.bean.ChangeStationBean;
import com.qianbei.bean.LandmarkTypeRequestBean;
import com.qianbei.bean.LighterRouerBean;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.bean.SearchBean;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;

import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * <pre>
 *     author : pwj
 *     e-mail : xxx@xx
 *     time   : 2019/03/14
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class AddLighterActivity extends BaseActivity {
    private static final String TAG = AddLighterActivity.class.getSimpleName();
    public static final int CODE_REQUEST_DRIVER = 100;
    public static final int CODE_REQUEST_VEHICLE = 101;
    @Bind(R.id.tv_origin)
    TextView tvOrigin;
    @Bind(R.id.tv_dest)
    TextView tvDest;
    @Bind(R.id.tv_driver)
    TextView tvDriver;
    @Bind(R.id.tv_vehicle)
    TextView tvVehicle;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_type)
    TextView tvType;
    private List<ChangeStationBean> stationBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lighter_add);
        ButterKnife.bind(this);
        setTitle("新增驳运");
        tvDate.setText(getNowDate());
    }

    @SuppressLint("SimpleDateFormat")
    private String getNowDate() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(new Date());
    }

    private void chooseLocations(final TextView textView) {
        if (stationBeans == null) {
            RequeastBean bean =
                    new RequeastBean1("select", "com.cygps.dubbo.commons.data.ICommonDataService",
                            new Basebean(), "WT_TransferStation");
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        try {
                            JSONArray js = sr.bodyData.optJSONArray("array");
                            stationBeans = JSON.parseArray(js.toString(), ChangeStationBean.class);
                            showDialogLocation(stationBeans, textView, "选择地点");
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            new ProgressDialog(mContext).OKpost1(sc, "正在加载...");
        } else {
            showDialogLocation(stationBeans, textView, "选择地点");
        }
    }

    /**
     * 中转站
     *
     * @param stationBeans
     * @param textView
     */
    private void showDialogLocation(final List<ChangeStationBean> stationBeans, final TextView textView, String title) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String[] texts = new String[stationBeans.size()];
        final int[] indexs = {0};
        for (int i = 0; i < stationBeans.size(); i++) {
            ChangeStationBean stationBean = stationBeans.get(i);
            texts[i] = stationBean.getName();
        }
        builder.setTitle(title)
                .setSingleChoiceItems(texts, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        indexs[0] = which;
                    }
                });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int index = indexs[0];
                String name = stationBeans.get(index).getName();
                String id = stationBeans.get(index).get_id();
                if (!TextUtils.equals(name, textView.getText().toString())) {
                    textView.setText(name);
                    textView.setTag(id);
                    tvDriver.setText("");
                }
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @OnClick({R.id.rl_origin, R.id.rl_dest, R.id.rl_driver,
            R.id.rl_vehicle, R.id.rl_date, R.id.tv_save, R.id.rl_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_origin:
                chooseLocations(tvOrigin);
                break;
            case R.id.rl_dest:
                chooseLocations(tvDest);
                break;
            case R.id.rl_driver:
                chooseDriver();
                break;
            case R.id.rl_vehicle:
                chooseVehicle();
                break;
            case R.id.rl_date:
                chooseDate(tvDate);
                break;
            case R.id.rl_type:
                chooseType();
                break;
            case R.id.tv_save:
                addRouter();
                break;
            default:
                break;
        }
    }

    /**
     * 选择业务类型
     */
    private void chooseType() {
        LandmarkTypeRequestBean requestBean = new LandmarkTypeRequestBean();
        requestBean.set_number(-1);
        requestBean.set_page(1);
        requestBean.set_pageSize(10);
        requestBean.set_sortField("number");
        requestBean.setD_id("5a026239343bab3b88214312");
        RequeastBean bean =
                new RequeastBean1("selectByPage", "com.cygps.dubbo.commons.data.ICommonDataService",
                        requestBean, "WT_DictDetail");
        ServerControl sc = new ServerControl(bean);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    try {
                        JSONArray js = sr.bodyData.optJSONArray("array");
                        List<ChangeStationBean> changeStationBeans = JSON.parseArray(js.toString(), ChangeStationBean.class);
                        showDialogLocation(changeStationBeans, tvType, "选择业务类型");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new ProgressDialog(mContext).OKpost1(sc, "正在加载...");
    }

    /**
     * 新增驳运路线
     */
    private void addRouter() {
        if (TextUtils.isEmpty(SetData.getUserID())) {
            new MsgAlert().show("userId为空，请重新登录");
            return;
        }
        if (TextUtils.isEmpty(tvType.getText())) {
            new MsgAlert().show("请选择业务类型");
            return;
        }
        if (TextUtils.isEmpty(tvOrigin.getText())) {
            new MsgAlert().show("请选择始发地");
            return;
        }
        if (TextUtils.isEmpty(tvDest.getText())) {
            new MsgAlert().show("请选择目的地");
            return;
        }
        if (TextUtils.isEmpty(tvDriver.getText())) {
            new MsgAlert().show("请选择司机名称");
            return;
        }
        if (TextUtils.isEmpty(tvVehicle.getText())) {
            new MsgAlert().show("请选择车牌号");
            return;
        }
        if (TextUtils.isEmpty(tvDate.getText())) {
            new MsgAlert().show("请选择日期");
            return;
        }
        if (TextUtils.equals(tvOrigin.getText(), tvDest.getText())) {
            new MsgAlert().show("始发地和目的地不能相同");
            return;
        }
        LighterRouerBean rouerBean = new LighterRouerBean();
        rouerBean._saveUserId = SetData.getUserID();
        rouerBean.date = tvDate.getText().toString();
        rouerBean.driver = tvDriver.getText().toString();
        rouerBean.driver_id = (String) tvDriver.getTag();
        rouerBean.vehicle = tvVehicle.getText().toString();
        rouerBean.vehicle_id = (String) tvVehicle.getTag();
        rouerBean.landmarkType = (String) tvType.getTag();
        rouerBean.trsferIds = new String[2];
        rouerBean.trsferIds[0] = (String) tvOrigin.getTag();
        rouerBean.trsferIds[1] = (String) tvDest.getTag();
        RequeastBean bean =
                new RequeastBean("addRouteBy",
                        "com.cygps.dubbo.WasteTransport.IPdaBoxnullAndLoadandunloadScan",
                        rouerBean);
        ServerControl sc = new ServerControl(bean);
        sc.serverListener = new ServerControl.ServerListener() {
            @Override
            public void serverFinish(ServerResult sr) {
                if (sr.isContinue) {
                    new MsgAlert().show("新增驳运工单成功");
                    finish();
                }
            }
        };
        new ProgressDialog(mContext).OKpost(sc, "正在保存...");
    }

    /**
     * 选择日期
     *
     * @param textView
     */
    private void chooseDate(final TextView textView) {
        Calendar c = Calendar.getInstance();
        Dialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                textView.setText(year + "-" + String.format("%02d", monthOfYear + 1) + "-" + dayOfMonth);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.show();
    }

    /**
     * 选择司机
     */
    private void chooseDriver() {
//        if (TextUtils.isEmpty(tvType.getText().toString())) {
//            new MsgAlert().show("请先选择业务类型");
//            return;
//        }
        //医废编码
        tvType.setTag("5a026258343bab3b88214313");
        String typeId = (String) tvType.getTag();
        Intent intent = new Intent(this, SearchActivity.class);
        intent.putExtra(SearchActivity.EXTRA_IS_DRIVER, true);
        intent.putExtra(SearchActivity.EXTAR_TYPE_ID, typeId);
        startActivityForResult(intent, CODE_REQUEST_DRIVER);
    }

    /**
     * 选择车牌号
     */
    private void chooseVehicle() {
        Intent intent = new Intent(this, SearchActivity.class);
        intent.putExtra(SearchActivity.EXTRA_IS_DRIVER, false);
        startActivityForResult(intent, CODE_REQUEST_VEHICLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_DRIVER && resultCode == SearchActivity.CODE_RESULT_DRIVER) {
            SearchBean searchBean = (SearchBean) data.getSerializableExtra(SearchActivity.RESULT_DATA);
            tvDriver.setText(searchBean.name);
            tvDriver.setTag(searchBean.id);
        } else if (requestCode == CODE_REQUEST_VEHICLE && resultCode == SearchActivity.CODE_RESULT_VEHICLE) {
            SearchBean searchBean = (SearchBean) data.getSerializableExtra(SearchActivity.RESULT_DATA);
            tvVehicle.setText(searchBean.name);
            tvVehicle.setTag(searchBean.id);
        }
    }
}
